home *** CD-ROM | disk | FTP | other *** search
- Path: anvil.ugrad.cs.ubc.ca!not-for-mail
- From: c2a192@ugrad.cs.ubc.ca (Kazimir Kylheku)
- Newsgroups: comp.lang.c,comp.unix.programmer
- Subject: Re: Q: '\n' character
- Date: 11 Apr 1996 10:55:17 -0700
- Organization: Computer Science, University of B.C., Vancouver, B.C., Canada
- Message-ID: <4kjh25INNf2e@anvil.ugrad.cs.ubc.ca>
- References: <4kj66f$k0o@ren.cei.net>
- NNTP-Posting-Host: anvil.ugrad.cs.ubc.ca
-
- In article <4kj66f$k0o@ren.cei.net>, <james lemley> wrote:
- >>>>Is there a function or some sort of way that I could remove '\n'
- >>>>charecter form the end of the string.
- >
- >fgets(buffer, file);
- >buffer[strlen(buffer)-1]=0;
- >
- >
- >It may not be the fastest, but it is darned near the easiest.
-
- It's also completely incorrect. What if there is no newline at the end?
-
- This is just part of a bullshit solution to the original problem which is to
- print lines from two files side by side.
-
- In implementing the solution, there is no need to build a string and then try
- to remove a trailing newline.
-
- Here is one solution that doesn't use its own buffers at all, though admittedly
- it does once call feof() on the file streams before anything is read from them
- for the sake of keeping everything in one tidy loop, rather than splitting
- into cases:
-
-
- #include <stdio.h>
-
- void concatprint(FILE *f1, FILE *f2)
-
- /*
- * read lines from f1 and f2 simultaneously, and print them side by side
- * f1 and f2 must be valid streams open for reading.
- */
-
- {
- int c;
-
- do {
- if (!feof(f1) && !ferror(f1))
- while ((c = getc(f1)) != '\n' && c != EOF)
- putchar(c);
- if (!feof(f2) && !ferror(f2))
- while ((c = getc(f2)) != '\n' && c != EOF)
- putchar(c);
- putchar('\n');
- } while ((!feof(f1) && !ferror(f1)) || (!feof(f2) && !ferror(f2)));
- }
-
- This is a complete, tested solution to the original posting, unlike some of the
- half-baked, unverified remarks that were posted in response, which completely
- miss the central problem anyway. There were calls for strtok(), fgets() and
- other nonsense, most of which were shown incorrect, anyway. That's like if I
- went to a doctor with my own ad-hoc diagnosis, and he prescribed a remedy for
- what I think is wrong with me instead of diagnosing.
-
- Patient: ``Doctor, I think I need to strip a newline from a string to make my
- program work!''
-
- Doctor: ``I won't bother looking at what your program is trying to do despite
- that you brought it with you; you obviously know what you are doing, and just
- need a little pointer. Here is a prescription for removing a newline that will
- sometimes work...''
- --
-
-